/**
 *  @Author YangYong  E-mail:yang2048@qq.com
 *  @Create 2017/9/13-20:06
 */
layui.use(['form','element','layer','table','jquery','upload'], function(){
    $ = layui.jquery,
    element = layui.element,
    form = layui.form,
    layer = parent.layer === undefined ? layui.layer : parent.layer,
    table = layui.table,
    upload = layui.upload;

    //验证
    form.verify({
        roleName: function (value, item) { //value：表单的值、item：表单的DOM对象
            if (value.length < 1) {
                return '角色名称不能为空';
            }
            if (!new RegExp("(^([\u0391-\uFFE5]|[a-zA-Z0-9]|[._-]){2,20}$)").test(value)) {
                return '用户名不合法(允许为2-20位汉字、字母、数字、"."、"-"、"_")';
            }
            if(/(^\_)|(\__)|(\_+$)/.test(value)){
                return '名称首尾不能出现下划线\'_\'';
            }
        }
    });

    // 监听表单提交
    form.on('submit(userEditForm)', function (data) {
        $.ajax({
            async: false,
            type: "POST",
            url: "/role/",
            data: data.field,
            dataType: 'json',
            success: function (res) {
                if (res.success) {
                    layer.open({
                        type: 1,
                        skin: 'layui-layer-rim',
                        area: ['420px', '240px'],
                        closeBtn: 0,
                        anim: 4,
                        shadeClose: true, //开启遮罩关闭
                        content: '角色名称：' + res.result.roleName+ '<hr/>'+
                        '角色标识：' + res.result.roleCode+ '<hr/>'+
                        '父级标识：' + res.result.roleParent+ '<hr/>'+
                        '状态：' + res.result.roleStatus+ '<hr/>',
                        end: function(){
                            var index = layer.getFrameIndex(window.name);
                            parent.layer.close(index);
                            parent.layer.msg('刷新才回显示修改内容哦！');
                        }
                    });
                } else {
                    parent.layer.msg(res.statusMessage, {icon: 5, time: 2000});
                }
            },
            error: function (res) {
                parent.layer.msg(res.statusMessage, {icon: 5, time: 2000});
            }
        });
    });

    //表格渲染
    table.render({
        elem: '#demo',
        cols:  [[ //标题栏
            {checkbox: true}
            /*,{index:true, title: '序号', width: 80,align:'center'}*/
            ,{field: 'roleName', title: '角色名称', width: 120,sort: true}
            ,{field: 'roleCode', title: '角色code', width: 120,align:'center'}
            ,{field: 'roleParent', title: '父级标识', width: 120}
            ,{field: 'updateBy', title: '添加人', width: 100}
            ,{field: 'roleStatus', title: '角色状态', width: 100,templet: '#userStatus'}
            ,{field: 'createTime', title: '添加时间', width: 190}
            ,{field: 'updateTime', title: '修改时间', width: 190}
            ,{field: 'permissionTitles', title: '权限名称', width: 200, style:'color: #2ab300;'}
            ,{field: 'permissionCodes', title: '权限识别', width: 200, style:'color: #7804ff;'}
            ,{field: 'right', title: '操作',toolbar: '#barDemo',align:'center',width:170, fixed:'right'}
        ]],
        //height: 315, //容器高度
        url: '/role/',
        //where: {token: '', id: 123} //如果无需传递额外参数，可不加该参数
        request: {pageName: 'curPage',limitName: 'pageSize'},
        response: {
            statusName: 'statusCode' //数据状态的字段名称，默认：code
            ,statusCode: '200' //成功的状态码，默认：0
            ,msgName: 'statusMessage' //状态信息的字段名称，默认：msg
            ,countName: 'totalCount' //数据总数的字段名称，默认：count
            ,dataName: 'result' //数据列表的字段名称，默认：data
        },
        page:true,
        limit: 10,
        even: true, //开启隔行背景
        id:'demo'
    });

    //监听表格复选框选择
    table.on('checkbox(demo)', function(obj){
        console.log(obj)
    });
    //监听工具条
    table.on('tool(demo)', function(obj){
        var data = obj.data;
        if(obj.event === 'detail'){
            layer.alert(JSON.stringify(data))
        } else if(obj.event === 'del'){
            layer.confirm('确认要删除吗？', function(index){
                $.ajax({
                    async:false,
                    type: "DELETE",
                    url:"/role/" + data.id,
                    dataType: 'json',
                    success: function(res){
                        if(res.success){
                            layer.msg('成功', {
                                icon: 1,
                                time: 2000
                            }, function(){
                                obj.del();
                            });
                        }else {
                            parent.layer.msg(res.statusMessage, {icon: 5,time: 2000});
                        }
                    },
                    error:function(res){
                        parent.layer.msg(res.statusMessage, {icon: 5,time: 2000});
                        return false;
                    }
                });
                layer.close(index);
            });
        } else if(obj.event === 'edit'){
            layer.open({
                type: 2,
                title: '角色信息',
                shadeClose: true,
                shade: 0.3,
                anim: 1,
                maxmin: true, //开启最大化最小化按钮
                area: ['800px', '700px'],
                offset: '100px',
                content: '/role/'+data.id,
            });
        }
    });

    var active = {
        add: function(){ //获取选中数据
            layer.open({
                type: 2,
                title: '信息内容',
                shadeClose: true,
                shade: 0.3,
                maxmin: true,
                area: ['900px', '600px'],
                offset: '100px',
                content: ['/role/toEdit', 'no']
            });
        }
        ,delBatch: function(){
            var checkStatus = table.checkStatus('demo')
                ,data = checkStatus.data;
            if (data.length == 0){
                layer.msg('选中了：'+ data.length + ' 个');
            }else {
                layer.alert(JSON.stringify(data));
            }
        }
    };

    $('.haerdTable .layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

});